package com.jianbing.util.gjj;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jianbing.dao.MongoDBDao;
import com.jianbing.entity.GjjLoginParam;
import com.jianbing.exception.ServiceException;
import com.jianbing.util.ColletionUtils;
import com.jianbing.util.StringUtils;
import com.jianbing.util.TableUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hantixiang on 12/1/2016.
 */
public class GjjLoginParamUtils {
    public static final String LOGIN_TYPE_ID = "loginTypeId", LOGINSTEPDETAIL = "loginStepDetail", LOGINPARAM = "loginParam";
    public static final String NEXTSTEP = "nextStep", CURRENTSTEP = "currentStep", PRESTEP = "preStep";
    public static final String NAME = "name", NOTE = "note", TYPE = "type";
    public static final String STRING_TYPE = "string", RADIO_TYPE = "radio";

    public static JSONObject getFirstStep(String jsonString, String loginTypeId) throws ServiceException {
        if (StringUtils.isEmpty(loginTypeId)) {
            throw new ServiceException("loginTypeId must input");
        }
        List<JSONObject> jsonObjectList = getFirstStepList(jsonString);
        if (ColletionUtils.isEmpty(jsonObjectList)) {
            return null;
        }
        for (JSONObject object : jsonObjectList) {
            if (object.get(LOGIN_TYPE_ID).toString().equals(loginTypeId)) {
                return object;
            }
        }
        return null;
    }


    public static void checkLoginParamFormat(String jsonString) throws ServiceException {
        try {
            List<JSONObject> firstStepList = GjjLoginParamUtils.getFirstStepList(jsonString);
            List<GjjLoginParam> list = MongoDBDao.queryForList(TableUtils.getTableName(GjjLoginParam.class), null, GjjLoginParam.class);
            for (JSONObject obj : firstStepList) {
                JSONObject object = obj;
                checkCurrentStepParamValid(object, list);
                String loginTypeId = object.get(LOGIN_TYPE_ID).toString();
                while (((JSONObject) object.get(LOGINSTEPDETAIL)).get(NEXTSTEP) != null) {
                    int nextStep = Integer.parseInt(((JSONObject) object.get(LOGINSTEPDETAIL)).get(NEXTSTEP).toString());
                    object = getCurrentStep(jsonString, loginTypeId, nextStep);
                    if (object == null) {
                        throw new ServiceException("loginTypeId:" + loginTypeId + "nextStep:" + nextStep + "配置不正确");
                    } else {
                        checkCurrentStepParamValid(object, list);
                    }
                }
            }
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 检查当前配置项是否合法
     *
     * @param object
     * @param list
     * @throws ServiceException
     */
    private static void checkCurrentStepParamValid(JSONObject object, List<GjjLoginParam> list) throws ServiceException {
        JSONArray array = getLoginParamDetail(object);
        if (array == null || array.size() == 0) {
            return;
        }
        String type = null;
        String name = null;
        for (int i = 0; i < array.size(); i++) {
            JSONObject param = (JSONObject) array.get(i);
            if (!(param.containsKey(NOTE) && param.containsKey(NAME) && param.containsKey(TYPE))) {
                throw new ServiceException("登陆配置项请确认至少包含name,note,type");
            } else {
                //check Name
                type = param.get(TYPE).toString();
                name = param.get(NAME).toString();
                if (STRING_TYPE.equals(type) && StringUtils.isNotEmpty(name) && !isInvalidName(name, list)) {
                    throw new ServiceException("你输入的参数" + name + "不在允许的列表中");
                } else if (RADIO_TYPE.equals(type)) {
                    try {
                        JSONObject.parse(name);
                    } catch (Exception e) {
                        throw new ServiceException("你输入的参数" + name + "不是JSON格式");
                    }
                }
            }
        }
    }

    private static boolean isInvalidName(String name, List<GjjLoginParam> list) {
        if (ColletionUtils.isEmpty(list)) return true;
        if (StringUtils.isEmpty(name)) return false;
        for (GjjLoginParam gjjLoginParam :
                list) {
            if (gjjLoginParam.getName().equals(name)) {
                return true;
            }
        }
        return false;
    }

    public static List<JSONObject> getFirstStepList(String jsonString) throws ServiceException {
        if (StringUtils.isEmpty(jsonString)) {
            throw new ServiceException("jsonString must input");
        }
        JSONArray loginCityParam = null;
        try {
            loginCityParam = JSON.parseArray(jsonString);
        } catch (Exception e) {
            throw new ServiceException("不是正确的JSON数组格式");
        }

        List<JSONObject> list = new ArrayList<>();
        for (int i = 0; i < loginCityParam.size(); i++) {
            JSONObject object = (JSONObject) loginCityParam.get(i);
            JSONArray paramArray = (JSONArray) object.get(LOGINSTEPDETAIL);
            JSONObject object1 = new JSONObject();
            if (object.get(LOGIN_TYPE_ID) == null) {
                throw new ServiceException("loginTypeId not exist");
            }
            object1.put(LOGIN_TYPE_ID, object.get(LOGIN_TYPE_ID).toString());
            object1.put(LOGINSTEPDETAIL, getFirstStep(paramArray));
            list.add(object1);
        }
        return list;
    }

    public static JSONArray getLoginParamDetail(JSONObject object) throws ServiceException {
        return (JSONArray) ((JSONObject) object.get(LOGINSTEPDETAIL)).get(LOGINPARAM);
    }


    public static JSONObject getCurrentStep(String jsonString, String loginTypeId, Integer currentStep) {
        if (StringUtils.isEmpty(loginTypeId) || currentStep == null) {
            return null;
        }
        JSONArray loginCityParam = JSON.parseArray(jsonString);
        List<JSONObject> list = new ArrayList<JSONObject>();
        for (int i = 0; i < loginCityParam.size(); i++) {
            JSONObject object = (JSONObject) loginCityParam.get(i);
            JSONArray paramArray = (JSONArray) object.get(LOGINSTEPDETAIL);
            if (loginTypeId.equals(object.get(LOGIN_TYPE_ID).toString())) {
                for (int j = 0; j < paramArray.size(); j++) {
                    JSONObject objectResult = (JSONObject) paramArray.get(j);
                    if (objectResult.get(CURRENTSTEP) != null) {
                        int currentStep2 = Integer.valueOf(objectResult.get(CURRENTSTEP).toString());
                        if (currentStep == currentStep2) {
                            JSONObject object1 = new JSONObject();
                            object1.put(LOGIN_TYPE_ID, loginTypeId);
                            object1.put(LOGINSTEPDETAIL, objectResult);
                            return object1;
                        }
                    }
                }
            }
        }
        return null;
    }

    private static JSONObject getFirstStep(JSONArray jsonArray) {
        for (int j = 0; j < jsonArray.size(); j++) {
            JSONObject object1 = (JSONObject) jsonArray.get(j);
            if (object1.get(PRESTEP) == null) {
                return object1;
            }
        }
        return null;
    }


}
